package com.sxm.yiwei.fragments;


import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.R;
import com.sxm.yiwei.activitis.AddCloseActivity;
import com.sxm.yiwei.activitis.AddLinkmanActivity;
import com.sxm.yiwei.activitis.HelpActivity;
import com.sxm.yiwei.activitis.HopeSengActivity;
import com.sxm.yiwei.activitis.HotSendActivity;
import com.sxm.yiwei.activitis.MineRecipients;
import com.sxm.yiwei.activitis.OnceSendActivity;
import com.sxm.yiwei.activitis.SlideListView;
import com.sxm.yiwei.adapters.SListViewSlideAdapter;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 *
 */


public class LinkReciverFragment extends Fragment implements View.OnClickListener{

    private Button recipientsadd;
    private SlideListView servicerlist;
    private ImageView linkrecipentsback;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private List<HashMap<String,String>>linkList;
    private HashMap<String,String>map;
    private JSONArray array;
    private String is = "1";
    private static final int ADDRESSTWO = 1002;
    private static final int ADDRESSONE = 1001;
    private Intent in;
    private String from;
    private ImageView nodata;
    private SListViewSlideAdapter slideAdapter;

    public LinkReciverFragment() {
        // Required empty public constructor
    }

    @Override
    public void onStart() {
        super.onStart();
       /* linkList.clear();
        getsLinkdata();*/
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_link_reciver, container, false);

        servicerlist = (SlideListView)view.findViewById(R.id.servicerlist);
        sharedPreferences =getActivity().getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "0");
        userId = sharedPreferences.getString("userId", "1");
        token = sharedPreferences.getString("token", "2");
        nodata = (ImageView) view.findViewById(R.id.reciver_nodata);
        Intent intent = getActivity().getIntent();
        from = intent.getStringExtra("from");
        linkList = new ArrayList<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                linkList.clear();
                getsLinkdata();
            }
        }).start();


        return view;

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden){
            return;
        }else {
            linkList.clear();
            getsLinkdata();
        }
    }

    // 获取联系人数据
    private List getsLinkdata() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/contact/getContactList");
        params.addHeader("Content-Type","application/json");
        params.addHeader("token", token);
        params.addHeader("appId", appId);
        params.addHeader("userId", userId);
        JSONObject j = new JSONObject();
        j.put("type","1");
        params.addParameter("params",j.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                getData(result);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(getActivity(),ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
        return linkList;
    }

    private void getData(String result) {

        com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
        String data = obj.getString("data");
        array = JSONArray.parseArray(data);
        if (array.size()==0){

        }else {
            nodata.setVisibility(View.GONE);
            for (int i = 0; i < array.size(); i++) {
                map = new HashMap();
                com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(String.valueOf(array.get(i)));
                String name = obj1.getString("name");
                String longitude = obj1.getString("longitude");
                String latitude = obj1.getString("latitude");
                String phone = obj1.getString("phone");
                String address = obj1.getString("address");
                String id = obj1.getString("id");

                map.put("name",name);
                map.put("phone",phone);
                map.put("address",address);
                map.put("id",id);
                map.put("longitude",longitude);
                map.put("latitude",latitude);

                linkList.add(map);
                // 设置listview
            }
        }


        slideAdapter = new SListViewSlideAdapter(getActivity(),linkList);
        servicerlist.setAdapter(slideAdapter);


        slideAdapter.setOnClickListenerEditOrDelete(new SListViewSlideAdapter.OnClickListenerEditOrDelete() {
            @Override
            public void OnClickListenerEdit(int position) {

                //编辑
                Intent intent  = new Intent(getActivity(),AddLinkmanActivity.class);
                HashMap<String, String> bianji = linkList.get(position);
                String name1 = bianji.get("name");
                String phone1 = bianji.get("phone");
                String address1 = bianji.get("address");
                intent.putExtra("name1",name1);
                intent.putExtra("phone1",phone1);
                intent.putExtra("address1",address1);
                intent.putExtra("is",is);
                startActivity(intent);
                linkList.remove(position);
            }

            @Override

            public void OnClickListenerDelete(final int position) {

                // 删除
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),R.style.NoBackGroundDialog);
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.cancel_servicedialog, null);

                builder.setView(view);
                Button cancelbt = (Button) view.findViewById(R.id.cancel_cancelbt);
                Button surebt = (Button) view.findViewById(R.id.cancel_surebt);
                TextView t2 = (TextView) view.findViewById(R.id.cancel_t2);
                t2.setText("是否删除此联系人 ?");
                final AlertDialog dialog = builder.create();
                cancelbt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                surebt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        HashMap<String, String> hashMap = linkList.get(position);
                        String id1 = hashMap.get("id");
                        removeLink(id1,position);
                        slideAdapter.notifyDataSetChanged();
                        dialog.dismiss();
                    }
                });
                dialog.show();



            }
        });

        if (from.equals("2")){
            servicerlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    HashMap<String, String> hashMap = linkList.get(position);
                    String name1 = hashMap.get("name");
                    String address1 = hashMap.get("address");
                    String phone1 = hashMap.get("phone");
                    String id1 = hashMap.get("id");
                    Intent intent = new Intent(getActivity(), HelpActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("name",name1);
                    bundle.putString("address",address1);
                    bundle.putString("phone",phone1);
                    bundle.putString("id",id1);
                    intent.putExtras(bundle);
                    getActivity().setResult(Activity.RESULT_OK,intent);
                    getActivity().finish();
                }
            });
        }
        slideAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.link_recipents_back:
                break;
            case R.id.recipients_addbt:
                Intent intent = new Intent(getActivity(),AddLinkmanActivity.class);

                intent.putExtra("is", is);
                startActivity(intent);
                break;

        }
    }

    private void removeLink(String id, final int position) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/contact/removeContact");
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject j = new JSONObject();
        j.put("contactId",id);
        params.setBodyContent(j.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                linkList.remove(position);
                try {
                    servicerlist.turnToNormal();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                servicerlist.invalidate();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(getActivity(),ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }

}
